from uuid import UUID
from fastapi import APIRouter, Depends, status
from sqlalchemy.ext.asyncio import AsyncSession

from core import relation as relation_core
from schemas.relation import RiskGuaranteeRelationCreate, RiskGuaranteeRelationResponse
from db.session import get_db
from log import log_api

router = APIRouter(
    prefix="/relations",
    tags=["relations"]
)

@router.post(
    "/",
    response_model=RiskGuaranteeRelationResponse,
    status_code=status.HTTP_201_CREATED
)
async def create_relation(
    relation: RiskGuaranteeRelationCreate,
    db: AsyncSession = Depends(get_db)
) -> RiskGuaranteeRelationResponse:
    """创建风险与保障关联关系"""
    log_api(f"Creating risk-guarantee relation: {relation}", module="router.relation")
    return await relation_core.create_risk_guarantee_relation(db, relation)

@router.get(
    "/{relation_id}",
    response_model=RiskGuaranteeRelationResponse
)
async def get_relation(
    relation_id: UUID,
    db: AsyncSession = Depends(get_db)
) -> RiskGuaranteeRelationResponse:
    """获取指定ID的关联关系"""
    log_api(f"Getting risk-guarantee relation by ID: {relation_id}", module="router.relation")
    return await relation_core.get_risk_guarantee_relation(db, relation_id)

@router.get(
    "/risk/{risk_item_id}",
    response_model=list[RiskGuaranteeRelationResponse]
)
async def get_relations_by_risk(
    risk_item_id: UUID,
    db: AsyncSession = Depends(get_db)
) -> list[RiskGuaranteeRelationResponse]:
    """获取指定风险项的所有关联关系"""
    log_api(f"Getting risk-guarantee relations for risk item: {risk_item_id}", module="router.relation")
    return await relation_core.get_relations_for_risk(db, risk_item_id)

@router.put(
    "/{relation_id}",
    response_model=RiskGuaranteeRelationResponse
)
async def update_relation(
    relation_id: UUID,
    relation_data: RiskGuaranteeRelationCreate,
    db: AsyncSession = Depends(get_db)
) -> RiskGuaranteeRelationResponse | None:
    """
    更新风险与保障关联关系
    
    - **relation_id**: 关联关系ID
    - **relation_data**: 更新后的关联关系数据
    """
    log_api(f"Updating risk-guarantee relation: {relation_id}", module="router.relation")
    updated_relation = await relation_core.update_risk_guarantee_relation(
        db=db,
        relation_id=relation_id,
        relation_data=relation_data
    )
    if updated_relation is None:
        from fastapi import HTTPException
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Relation with id {relation_id} not found"
        )
    return updated_relation

@router.delete(
    "/{relation_id}",
    status_code=status.HTTP_204_NO_CONTENT
)
async def delete_relation(
    relation_id: UUID,
    db: AsyncSession = Depends(get_db)
):
    """删除指定ID的关联关系"""
    log_api(f"Deleting risk-guarantee relation by ID: {relation_id}", module="router.relation")
    return await relation_core.delete_risk_guarantee_relation(db, relation_id) 